package com.example.badmintonCommon.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.*;
import java.util.List;

public class JsonTypeHandler<T> extends BaseTypeHandler<T> {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final Class<T> type;

    public JsonTypeHandler() {
        this.type = (Class<T>) Object.class;
    }

    public JsonTypeHandler(Class<T> type) {
        if (type == null) throw new IllegalArgumentException("类型参数不能为空");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new SQLException("无法将参数转换为JSON字符串: " + parameter, e);
        }
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    @SuppressWarnings("unchecked")
    private T parseJson(String json) throws SQLException {
        if (json == null || json.isEmpty()) {
            return getDefaultValue();
        }

        try {
            // 特殊处理数组类型
            if (type.isArray()) {
                Class<?> componentType = type.getComponentType();

                if (componentType == int.class) {
                    // 处理 int[] 类型
                    return (T) objectMapper.readValue(json, int[].class);
                } else if (componentType.isArray() && componentType.getComponentType() == int.class) {
                    // 处理 int[][] 类型
                    JsonNode node = objectMapper.readTree(json);
                    if (node.isArray()) {
                        if (node.get(0).isArray()) {
                            // 已经是二维数组
                            int[][] result = new int[node.size()][];
                            for (int i = 0; i < node.size(); i++) {
                                JsonNode innerNode = node.get(i);
                                int[] innerArray = new int[innerNode.size()];
                                for (int j = 0; j < innerNode.size(); j++) {
                                    innerArray[j] = innerNode.get(j).asInt();
                                }
                                result[i] = innerArray;
                            }
                            return (T) result;
                        } else {
                            // 一维数组转换为二维数组
                            int[] oneD = objectMapper.readValue(json, int[].class);
                            int[][] twoD = new int[1][];
                            twoD[0] = oneD;
                            return (T) twoD;
                        }
                    }
                }
            }

            // 其他类型正常解析
            return objectMapper.readValue(json, type);
        } catch (IOException e) {
            throw new SQLException("无法解析 JSON: " + json, e);
        }
    }

    @SuppressWarnings("unchecked")
    private T getDefaultValue() {
        if (type == int[].class) {
            return (T) new int[24];
        } else if (type == int[][].class) {
            return (T) new int[7][24];
        }
        return null;
    }
}

